$(document).ready(function(){
	// //新增用户弹出窗口中用户类型默认选第一个
	
 		// 帐户名验证
	    jQuery.validator.addMethod("isUsername", function(value, element) {
	        // var username = /^[0-9_a-zA-Z]\w{2,30}$/g;
	        var username = /^[\u0391-\uFFE5\w]+$/;
	        return this.optional(element) || (username.test(value));
	    }, "不能输入特殊字符，");
	    
	    //昵称验证
	    jQuery.validator.addMethod("isPassword", function(value, element) {

	    	 var password = /^[\u0391-\uFFE5\w]+$/; //校验字符中是否包含非法字符

	    	 // var chn =  /[^u4e00-u9fa5]/; //校验是否为中文
	        // return this.optional(element) || ( (password.test(value)) && (!chn.test(value))  );
	        return this.optional(element) || ( (password.test(value))   );
	    }, "不能输入特殊字符，请正确输入");

 		jQuery.validator.addMethod("isMobile", function(value, element) {
	        var length = value.length;
	        var mobile = /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)+$/g;
	        return this.optional(element) || (mobile.test(value));
	    }, "请正确填写您的手机号码");
	

 		$("#addAdminForm").validate({
			event: "keyup" ,
			rules:{
				username:{
					isUsername:true,
					required:true,
					minlength:3,
					maxlength:30
				},
				password:{
					required:true,
					minlength:6,
					maxlength:60
				},
				crmPassword:{
					required:true,
					equalTo:"#input-addAdmin-password"
				},
				name:{
					required:true,
					minlength:3,
					maxlength:30
				},
				telephone:{
					isMobile:true
				},
				address:{
					maxlength:120
				}
			},
			messages:{
				username:{
					required:"请输入用户名",
					minlength: "用户名长度至少为 3字符",
					maxlength: "用户名长度最大为 30 字符"
				},
				password:{
					required: "请输入密码",
					minlength: "密码至少输入 6字符",
					maxlength: "密码长度最大为 60 字符"
				},
				crmPassword:{
					required: "请再次输入密码",
					equalTo: "密码输入不一致"
				},
				name:{
					required:"请输入姓名",
					minlength: "姓名长度至少为 3字符",
					maxlength: "姓名长度最大为 30 字符"
				},
				telephone:{
					isMobile:"请正确输入电话号码"
				},
				address:{
					maxlength: "联系地址长度最大为 120 字符"
				}
			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});

	$("#editAdminForm").validate({
			event: "keyup" ,
			rules:{
				username:{
					isUsername:true,
					required:true,
					minlength:3,
					maxlength:30
				},
				name:{
					required:true,
					minlength:3,
					maxlength:30
				},
				telephone:{
					isMobile:true
				},
				address:{
					maxlength:120
				}
			},
			messages:{
				username:{
					required:"请输入用户名",
					minlength: "用户名长度至少为 3字符",
					maxlength: "用户名长度最大为 30 字符"
				},
				name:{
					required:"请输入姓名",
					minlength: "姓名长度至少为 3字符",
					maxlength: "姓名长度最大为 30 字符"
				},
				telephone:{
					isMobile:"请正确输入电话号码"
				},
				address:{
					maxlength: "联系地址长度最大为 120 字符"
				}
			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});


	$("#setPasswordForm").validate({
			event: "keyup" ,
			rules:{
				password:{
					required:true,
					minlength:6,
					maxlength:30,
					isPassword:true
				},
				edit_crmPassword:{
					equalTo: "#editpsw-password"
				}
			},
			messages:{
				password:{
					required:"请输入密码",
					minlength: "密码至少输入6字符",
					maxlength: "密码长度最大为 60 字符"
				},
				edit_crmPassword:{
					required:"请再次输入密码",
					equalTo: "密码输入不一致"
				}

			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});
});

/* 获取多选框项id */
function getIds() {
	var checkIds = [];
	// alert($("#userList input[type='checkbox']").length)
	$("#adminListBody input[type='checkbox']").each(function(index) {

		if ($(this).is(':checked')) {
			var id = $(this).val();
			checkIds.push(id);
		}
	});

	return checkIds;
}


function showAddAdminModal(){
	$("#input-addAdmin-username").html("");
	$("#input-addAdmin-password").html("");
	$("#input-addAdmin-name").html("");
	$("#input-addAdmin-telephone").html("");
	$("#input-addAdmin-address").html("");

	$('#addAdminModal').modal("show");
}

function addAdmin() {
	
	var username = $("#input-addAdmin-username");
	var password = $("#input-addAdmin-password");
	var name = $("#input-addAdmin-name");
	var sex = $("#input-addAdmin-sex");
	var telephone = $("#input-addAdmin-telephone");
	var address = $("#input-addAdmin-address");
	var addAdminForm = $("#addAdminForm");

	if(addAdminForm.valid()==false){
		// bootbox.alert("请正确输入相关信息");
		return false;
	}

	var data = $('#addAdminForm').serialize();
	
	$.ajax({
		url : $('#addAdminForm').attr("action"),
		type : 'post',
		data : data,
		dataType : "json",
		headers : {
			Accept : "application/json; charset=utf-8"
		},
		contentType : "application/x-www-form-urlencoded; charset=utf-8",
		success : function(result) {
				// console.log(result);
			if(result.result == "success"){
				bootbox.alert("新增成功",function(){
					window.location.reload()
					$('#addUserModal').modal("hide");
				});
				
			} else {
				bootbox
						.alert(result.message);
			}
			
		},
		error : function(xhr) {
			bootbox
					.alert(xhr.responseText);
		}
	});

}

function deleteAdmins() {
	var ids = getIds();

	if (ids.length == 0) {
		bootbox.alert("请至少选择一项");
		return;
	}
	bootbox.confirm("确定要删除用户吗？",function(result){
		if(result){
			console.log(ids);
			var data = [ {
				name : 'ids',
				value : ids
			} ];
			var requrl = ctx + "/mam-rbac/admins/delete";
			$.ajax({
				url : requrl,
				type : 'post',
				data : data,
				dataType : "json",
				headers : {
					Accept : "application/json; charset=utf-8"
				},
				contentType : "application/x-www-form-urlencoded; charset=utf-8",
				success : function(result) {
					if(result.result == "success"){
						bootbox.alert("删除成功",function(){
							var f = $("#search-form");
							f.submit();
						});
					} else {
						bootbox
						.alert(result.message);
					}
				},
				error : function() {
					bootbox.alert('删除失败');
				}
			});
		}else{
			return;
		}
		
	});
	
}

function setAdminStatus(id, status) {

	//目前状态只有 n 和 d，直接至反。。
	if(status=="s"){
		status = "n";
	}else{
		status = "s";
	}

	var data = [ {
		name : 'id',
		value : id
	}, {
		name : 'status',
		value : status
	} ];
	var requrl = ctx + "/mam-rbac/admins/change_status";
	$.ajax({
		url : requrl,
		type : 'post',
		data : data,
		dataType : "json",
		headers : {
			Accept : "application/json; charset=utf-8"
		},
		contentType : "application/x-www-form-urlencoded; charset=utf-8",
		success : function(result) {
			if(result.result=='success'){
				bootbox.alert("修改状态成功",function(){
					var f = $("#search-form");
					f.submit();	
				});	
			} else {
				bootbox
				.alert(result.message);
			}
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});
}


function showPasswordModal(adminId,username){
	var ed_userId = $('#editpsw-adminId');
	var ed_username = $('#editpsw-username');
	var ed_password = $('#editpsw-password');
	var ed_password_confirm = $('#editpsw-password-confirm');
	var lb_username = $('#editpsw-lb_username');
	var btn_submitPassword = $("#btn-submitPassword");

	ed_userId.val(adminId);
	ed_username.val(username);
	lb_username.html(username);
	
	ed_password.val("");
	ed_password_confirm.val("");

	btn_submitPassword.unbind('click');
	btn_submitPassword.on('click',function(){
		// alert(ed_password.val());
		// alert(userID+" ");
		setPassword(adminId,ed_password.val());
	});
	$("#setPasswordModal").modal("show");
}

function setPassword(adminId,password) {
	var form = $("#setPasswordForm");

	if( !form.valid() ){
		return;
	}

	var data = [ {name : 'id'		,	value : adminId} ,
				 {name : 'password'	, 	value : password}];
	$.ajax({
		url : form.attr("action"),
		type : 'post',
		data : data,
		dataType : "json",
		headers : {
			Accept : "application/json; charset=utf-8"
		},
		contentType : "application/x-www-form-urlencoded; charset=utf-8",
		success : function(result) {
			if(result.result=="success"){
				bootbox.alert("修改密码成功",function(){
					$("#setPasswordModal").modal("hide");
				});

			}else{
				bootbox
				.alert(result.message);
			}
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});
}

function editAdmin(adminId) {
	var ed_userId = $('#editAdmin-adminId');
	var ed_username = $('#editAdmin-username');
	var lb_username = $('#editAdmin-lb_username');
	var ed_name = $('#editAdmin-name');
	var ed_address = $('#editAdmin-address');
	var ed_telephone = $('#editAdmin-telephone');
	var sex = $("#editAdmin-sex input[type='radio']");

	var btn_submitUserInfo = $("#btn-submitUserInfo");

	btn_submitUserInfo.on('click',function(){
		submitEditAdmin(adminId);
	})

	// ajax请求
	var data = [ {
		name : 'id',
		value : adminId
	} ];
	var requrl = ctx + "/mam-rbac/admins/get";
	$.ajax({
		url : requrl,
		type : 'post',
		data : data,
		dataType : "json",
		headers : {
			Accept : "application/json; charset=utf-8"
		},
		contentType : "application/x-www-form-urlencoded; charset=utf-8",
		success : function(result) {
			var admin = result.data;
			// 填装数据
			ed_name.attr('value', admin.name);
			ed_username.attr('value', admin.username);
			lb_username.html(admin.username);
			//ed_status.attr('value', admin.status);
			ed_address.attr('value', admin.address);
			ed_userId.attr('value', admin.id);
			ed_telephone.attr('value',admin.telephone);
			sex.each(function(index){

				if($(this).val() == admin.sex){
					sex[index].checked=true;
				}
			});

			// 打开窗口
			$('#editAdminModal').modal("show");
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});

}

function submitEditAdmin(adminId){
	
	var form = $("#editAdminForm");
	console.log(form);
	if(!form.valid()){
		// bootbox.alert("输入不合法，请重新输入");
        return;
	}
    $.ajax({
            //cache: true,
            type: "POST",
            url:form.attr("action"),
            data: form.serialize(),// 你的formid
            //async: false,
    		dataType : "json",
			headers : {
				Accept : "application/json; charset=utf-8"
			},
			contentType : "application/x-www-form-urlencoded; charset=utf-8",
            success: function(result) {
            	if(result.result=="success"){
            		bootbox.alert("更新信息成功",function(){
                        window.location.reload();
                        $("#editAdminModal").modal('hide');
                        $("#btn-submitUserInfo").unbind('click');
                    });
    			}else{
    				bootbox
    				.alert(result.message);
    			}

            },
            error: function(request) {
                // alert("Connection error");
                bootbox.alert("提交失败");
            },
    });


}


function selectAll(id,parent){
	var selectAllCheckbox = $("#"+id);
	var checkList = $("#"+parent+" input[type='checkbox']");
	if(selectAllCheckbox.is(':checked')){
		checkList.each(function(index) {
			this.checked = true;
		});
	}else{
		checkList.each(function(index) {
			this.checked = false;
		});
	}
}
